package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


// 购物车
@Service
@Transactional
public class CartServiceImpl implements CartService {
    //注入mapper
    @Autowired
    private CartMapper cartMapper;

    //添加购物车
    @Override
    public Cart add(Cart cartParm) {
        //1.先查询购物车是否有此项数据
        //1-1创建表达式
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());//用户id
        qw.eq(cartParm.getDishId() != null, Cart::getDishId, cartParm.getDishId()); //菜品id
        qw.eq(cartParm.getSetmealId() != null, Cart::getSetmealId, cartParm.getSetmealId()); //套餐id
        Cart cart = cartMapper.selectOne(qw); //查询用户购物车
        //2.判断
        if (cart == null) { //不存在新增
            cart = cartParm;
            cart.setUserId(UserHolder.get().getId()); //补全用户信息
            cart.setNumber(1); //补全数量
            cart.setCreateTime(new Date()); //补全添加购物车时间
            cartMapper.insert(cart);//添加到购物车
        } else { //存在的话,数量+1 更新数据库
            cart.setNumber(cart.getNumber() + 1); //购物车数量+1
            cartMapper.updateById(cart);//修改购物车数量
        }
        //返回购物车
        return cart;
    }

    //查询购物车
    @Override
    public List<Cart> list() {
        //1.构建条件
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId()); //通过用户id查看购物车
        //查询并返回
        return cartMapper.selectList(qw);
    }

    //清空购物车
    @Override
    public void clean() {
        //构建条件
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId()); //用户id
        //2.执行删除
        cartMapper.delete(qw);
    }

    //修改购物车
    @Override
    public Cart sub(Cart cartParm) {
        //创建表达式
        LambdaQueryWrapper<Cart> qw = new LambdaQueryWrapper<>();
        qw.eq(Cart::getUserId, UserHolder.get().getId());//用户id
        qw.eq(cartParm.getDishId() != null, Cart::getDishId, cartParm.getDishId()); //菜品id
        qw.eq(cartParm.getSetmealId() != null, Cart::getSetmealId, cartParm.getSetmealId()); //套餐id
        Cart cart = cartMapper.selectOne(qw); //查询用户购物车
        //购物车数量-1
        cart.setNumber(cart.getNumber() - 1); //购物车数量+1
        if (cart.getNumber()==0){
            cartMapper.delete(qw);
        }else {
            cartMapper.updateById(cart);//修改购物车数量
        }

        return cart;

    }


}
